////
////  QRScanner.swift
////  33web
////
////  Created by apple on 2025/7/29.
////
//
//import UIKit
//import LBXScan
//import AVFoundation
//
//class QRScanner: NSObject {
//    
//    // 扫描结果回调
//    typealias ScanResultHandler = (String) -> Void
//    
//    // 扫描样式配置
//    struct ScannerStyle {
//        var angleColor: UIColor = .systemBlue       // 扫描框边角颜色
//        var borderColor: UIColor = .white           // 扫描框边框颜色
//        var cornerWidth: CGFloat = 2.0              // 扫描框边角宽度
//        var borderWidth: CGFloat = 0.5              // 扫描框边框宽度
//        var cornerLength: CGFloat = 20              // 扫描框边角长度
//        var scannerLineName: String? = "qrcode_scan_light_green" // 扫描线图片
//        var animationInterval: TimeInterval = 0.02  // 扫描线动画间隔
//        var scannerAreaScale: CGFloat = 0.7         // 扫描区域占屏幕比例(宽度)
//    }
//    
//    private var scanViewController: LBXScanViewController?
//    private var resultHandler: ScanResultHandler?
//    
//    /// 开始扫描
//    /// - Parameters:
//    ///   - viewController: 呈现扫描界面的控制器
//    ///   - style: 扫描界面样式配置
//    ///   - resultHandler: 扫描结果回调
//    func startScan(from viewController: UIViewController,
//                   style: ScannerStyle = ScannerStyle(),
//                   resultHandler: @escaping ScanResultHandler) {
//        
//        // 检查相机权限
//        checkCameraPermission { [weak self] granted in
//            guard let self = self else { return }
//            
//            if granted {
//                DispatchQueue.main.async {
//                    self.setupScanner(from: viewController, style: style, resultHandler: resultHandler)
//                }
//            } else {
//                self.showPermissionAlert(from: viewController)
//            }
//        }
//    }
//    
//    private func setupScanner(from viewController: UIViewController,
//                              style: ScannerStyle,
//                              resultHandler: @escaping ScanResultHandler) {
//        
//        self.resultHandler = resultHandler
//        
//        // 设置扫码参数
//        let scanOption = LBXScanViewStyle()
//        scanOption.photoframeAngleStyle = .inner
//        scanOption.photoframeAngleW = style.cornerWidth
//        scanOption.photoframeAngleH = style.cornerLength
//        scanOption.photoframeLineW = style.borderWidth
//        scanOption.isNeedShowRetangle = true
//        scanOption.anmiationStyle = .lineMove
//        scanOption.colorAngle = style.angleColor
//        scanOption.colorRetangleLine = style.borderColor
//        scanOption.whRatio = 1.0
//        scanOption.centerUpOffset = 44
//        scanOption.xScanRetangleOffset = CGFloat(Int((1 - style.scannerAreaScale) * UIScreen.main.bounds.width / 2))
//        
//        if let lineImageName = style.scannerLineName {
//            scanOption.animationImage = UIImage(named: lineImageName)
//        }
//        
//        // 创建扫描控制器
//        let vc = LBXScanViewController()
//        configureScanStyle(for: scanOption)
//        vc.scanResultDelegate = self
//        vc.modalPresentationStyle = .fullScreen
//        vc.modalPresentationStyle = .fullScreen
//        
//        self.scanViewController = vc
//        viewController.present(vc, animated: true, completion: nil)
//    }
//    private func configureScanStyle(for scanType: SCANCODETYPE) -> LBXScanViewStyle {
//          var style = LBXScanViewStyle()
//          
//          // 基本配置
//          style.centerUpOffset = 44
//          style.photoframeAngleStyle = .inner
//          style.photoframeLineW = 4
//          style.photoframeAngleW = 28
//          style.photoframeAngleH = 16
//          style.isNeedShowRetangle = true
//          
//          // 根据扫码类型调整
//          switch scanType {
//          case .SCT_QRCode:
//              style.whRatio = 1.0
//              style.anmiationStyle = .netGrid
//          case .SCT_BarCodeITF:
//              style.whRatio = 4.3/2.18
//              style.anmiationStyle = .lineMove
//          case .SCT_BarEAN13:
//              style.whRatio = 1.0
//              style.anmiationStyle = .lineMove
//          case .SCT_BarCode93:
//              style.whRatio = 4.3/2.18
//              style.anmiationStyle = .lineMove
//          case .SCT_BarCode128:
//              style.whRatio = 4.3/2.18
//              style.anmiationStyle = .lineMove
//          @unknown default:
//              style.whRatio = 4.3/2.18
//              style.anmiationStyle = .lineMove
//          }
//          
//          style.colorRetangleLine = UIColor(red: 0.0, green: 0.7, blue: 0.0, alpha: 1.0)
//          style.colorAngle = UIColor(red: 0.0, green: 0.7, blue: 0.0, alpha: 1.0)
//          style.xScanRetangleOffset = 60
//          
//          return style
//      }
//    
//    /// 检查相机权限
//    private func checkCameraPermission(completion: @escaping (Bool) -> Void) {
//        let status = AVCaptureDevice.authorizationStatus(for: .video)
//        
//        switch status {
//        case .authorized:
//            completion(true)
//        case .notDetermined:
//            AVCaptureDevice.requestAccess(for: .video) { granted in
//                completion(granted)
//            }
//        default:
//            completion(false)
//        }
//    }
//    
//    /// 显示权限提示
//    private func showPermissionAlert(from viewController: UIViewController) {
//        DispatchQueue.main.async {
//            let alert = UIAlertController(
//                title: "相机权限未开启",
//                message: "请在设置中开启相机权限以使用扫码功能",
//                preferredStyle: .alert
//            )
//            
//            alert.addAction(UIAlertAction(title: "取消", style: .cancel))
//            alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
//                if let url = URL(string: UIApplication.openSettingsURLString) {
//                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
//                }
//            })
//            
//            viewController.present(alert, animated: true)
//        }
//    }
//    
//    /// 停止扫描
//    func stopScan() {
//        scanViewController?.stopScan()
//    }
//    
//    /// 重新开始扫描
//    func restartScan() {
//        scanViewController?.startScan()
//    }
//}
//
//// MARK: - LBXScanViewControllerDelegate
//extension QRScanner: LBXScanViewControllerDelegate {
//    func scanFinished(scanResult: LBXScanResult, error: String?) {
//        if let error = error {
//            print("扫描错误: \(error)")
//            return
//        }
//        
//        guard let result = scanResult.strScanned, !result.isEmpty else {
//            print("未识别到有效二维码")
//            return
//        }
//        
//        resultHandler?(result)
//    }
//}
//extension QRScanner {
//    /// 从图片识别二维码
//    func recognizeQRCode(from image: UIImage, completion: @escaping (String?) -> Void) {
//        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
//        
//        guard let ciImage = CIImage(image: image),
//              let features = detector?.features(in: ciImage) else {
//            completion(nil)
//            return
//        }
//        
//        for feature in features {
//            if let qrFeature = feature as? CIQRCodeFeature {
//                completion(qrFeature.messageString)
//                return
//            }
//        }
//        
//        completion(nil)
//    }
//    
//    /// 生成二维码
//    static func generateQRCode(content: String, size: CGSize, logo: UIImage? = nil) -> UIImage? {
//        guard let data = content.data(using: .utf8),
//              let filter = CIFilter(name: "CIQRCodeGenerator") else {
//            return nil
//        }
//        
//        filter.setValue(data, forKey: "inputMessage")
//        filter.setValue("H", forKey: "inputCorrectionLevel") // 容错级别
//        
//        guard let outputImage = filter.outputImage else { return nil }
//        
//        // 调整大小
//        let scaleX = size.width / outputImage.extent.size.width
//        let scaleY = size.height / outputImage.extent.size.height
//        let transformedImage = outputImage.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY))
//        
//        let qrImage = UIImage(ciImage: transformedImage)
//        
//        // 添加logo
//        if let logo = logo {
//            UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
//            qrImage.draw(in: CGRect(origin: .zero, size: size))
//            
//            let logoSize = CGSize(width: size.width * 0.2, height: size.height * 0.2)
//            let logoFrame = CGRect(x: (size.width - logoSize.width) / 2,
//                                  y: (size.height - logoSize.height) / 2,
//                                  width: logoSize.width,
//                                  height: logoSize.height)
//            
//            logo.draw(in: logoFrame)
//            let combinedImage = UIGraphicsGetImageFromCurrentImageContext()
//            UIGraphicsEndImageContext()
//            
//            return combinedImage
//        }
//        
//        return qrImage
//    }
//}
